// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Q [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// j [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/coa_entity.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/all_reports/journal/accounts_select_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';

@RouterMeta(paramName: "accountsSelectPage")
class AccountsSelectPage extends StatefulWidget {
  final bool isSelect;

  const AccountsSelectPage({Key key, this.isSelect}) : super(key: key);

  @override
  _AccountsSelectPageState createState() => _AccountsSelectPageState();
}

class _AccountsSelectPageState extends State<AccountsSelectPage>
    with PagePresenter<AccountsSelectPage, AccountsSelectProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.accounts,
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              key: ValueKey("Search Input"),
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            listBuilder<bool>(
                selector: (_, __) => __.searchController.text.isEmpty,
                builder: (BuildContext context, bool value, Widget child) =>
                    value == true ? child : AppSpaces.h20,
                child: _buildHeaderList()),
            Expanded(
                child: CupertinoScrollbar(
              child: listBuilder<List<CoaEntity>>(
                selector: (_, __) => __.data,
                builder: (BuildContext context, List<CoaEntity> value,
                    Widget child) {
                  List<Widget> children = [];
                  for (var i = 0; i < value.length; i++) {
                    final item = value[i];
                    final headerSearch = item.coaAccountHeader.where((element) {
                      final data = element.coaAccountDetail
                          .where((element) =>
                              RegExpUtils.getSearchRegExp(
                                      provider.searchController.text)
                                  .hasMatch(element.name) ||
                              RegExpUtils.getSearchRegExp(
                                      provider.searchController.text)
                                  .hasMatch(element.accountCode))
                          .toList();
                      if (data.length > 0) {
                        element.coaAccountDetail = data;
                        return true;
                      }
                      return false;
                    }).toList();
                    if (headerSearch.length > 0) {
                      children.add(Container(
                        key: provider.headerKey[i],
                        child: ListHeaderItem(
                          title: '${item.name}',
                        ),
                      ));
                      for (final i in headerSearch) {
                        children.addAll(i.coaAccountDetail
                            .map((e) => PressedOpacityButton(
                                  onPressed: () =>
                                      provider.onSelect(e, widget.isSelect),
                                  padding: EdgeInsets.only(
                                    left: getDp(25),
                                    top: getDp(9),
                                    bottom: getDp(9),
                                  ),
                                  child: listBuilder<bool>(
                                    selector: (_, __) =>
                                        __.currentSelectAccount?.id == e.id,
                                    builder: (BuildContext context, bool value,
                                            Widget child) =>
                                        NormalRadio(
                                      isSelect: value,
                                      isFix: true,
                                      title: '${e.name}',
                                    ),
                                  ),
                                ))
                            .toList());
                      }
                    }
                  }
                  return SingleChildScrollView(
                    controller: provider.scrollController,
                    child: Column(
                      children: children,
                    ),
                  );
                },
              ),
            )),
          ],
        ),
      );

  Widget _buildHeaderList() => listBuilder<int>(
        selector: (_, __) => __.data.length,
        builder: (BuildContext context, int value, Widget child) => Container(
          height: getDp(82),
          alignment: Alignment.centerLeft,
          child: ListView(
            padding: EdgeInsets.symmetric(horizontal: getDp(9)),
            scrollDirection: Axis.horizontal,
            children: List.generate(
              value,
              (index) => _buildHeaderItems(context, index),
            ).toList(),
          ),
        ),
      );

  Widget _buildHeaderItems(BuildContext context, int index) {
    return listBuilder<CoaEntity>(
      selector: (_, __) => __.data[index],
      builder: (BuildContext context, CoaEntity value, Widget child) => Center(
        child: PressedOpacityButton(
            padding: EdgeInsets.symmetric(
              horizontal: getDp(7),
            ),
            onPressed: () {
              provider.onSelectGroup(value, index);
            },
            child: listBuilder<bool>(
              selector: (_, __) => __.currentSelectGroup == value.name,
              builder: (BuildContext context, bool isSelect, Widget child) =>
                  Container(
                padding: EdgeInsets.symmetric(
                    horizontal: getDp(10), vertical: getDp(8)),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(getDp(5)),
                    color: isSelect ? aceBlueColor : Colors.white,
                    border: Border.all(
                      color: aceBlueColor,
                      width: getDp(1),
                    )),
                child: Text(
                  '${value.name}',
                  style: TextStyle(
                    color: isSelect ? Colors.white : aceBlueColor,
                    fontSize: getSp(14),
                    fontWeight: FontWeight.w700,
                    height: 1,
                  ),
                ),
              ),
            )),
      ),
    );
  }
}
